package com.cyy.view

import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.CharsetUtil
import cn.hutool.core.util.ReflectUtil
import cn.hutool.setting.Setting
import com.cyy.controller.CyyGenerator
import com.cyy.model.Constants
import com.cyy.model.GmodelModel
import com.cyy.srv.GenSrv
import com.jfinal.kit.Kv
import com.jfinal.kit.StrKit
import com.jfinal.plugin.activerecord.Config
import com.jfinal.plugin.activerecord.Db
import com.jfinal.plugin.activerecord.DbKit
import com.jfinal.plugin.activerecord.DbPro
import com.jfinal.plugin.activerecord.dialect.Dialect
import com.jfinal.plugin.activerecord.generator.TypeMapping
import com.jfinal.template.EngineConfig
import javafx.scene.control.ListView
import tornadofx.*
import java.util.*
import javax.sql.DataSource

class TopView(val gmodel: GmodelModel, val genSrv: GenSrv) : View("My View") {
    val engine = gmodel.engine.value
    var tbls = gmodel.tables
    lateinit var gen: CyyGenerator

    override val root = hbox(5) {
        button("测试连接") {
            action {
                if ((gmodel.dataSource.value != null)) {
                    Constants.closeDb(gmodel.dataSource.value)
                    gmodel.arp.value.stop()
                }
                when (gmodel.dbtype.value) {
                    "sqlite", "h2" -> {
                        // 每次点击"测试连接"测试连接时，都将之前保存的db和table列表清空
                        gmodel.tables.clear()
                        if (testDb1().not()) return@action

                    }
                    else -> {
                        // 每次点击"测试连接"测试连接时，都将之前保存的db和table列表清空
                        gmodel.dbs.clear()
                        gmodel.tables.clear()
                        if (testDb2().not()) return@action
                    }
                }
            }
        }
        button("Generate") {
            enableWhen(gmodel.dbOK)
            action {
                try {
                    val btp = gmodel.baseTemplatePath.value
                    val a = arrayListOf<String>()
                    val aa = arrayListOf<String>()
                    val c = gmodel.removedTableNamePrefixes.value.split(",")
//                    a.add("ay_")
//                    a.add("Ay_")
                    a.addAll(c)
                    val b = a.toTypedArray()
                    aa.addAll(gmodel.excludedTable)
                    val bb = aa.toTypedArray()
                    gmodel.metaBuilder.value.setRemovedTableNamePrefixes(*b)
                    gmodel.metaBuilder.value.addExcludedTable(*bb)
                    gmodel.metaBuilder.value.setTypeMapping(TypeMapping())

                    engine.setBaseTemplatePath(btp)
                    gen = CyyGenerator(gmodel.dataSource.value, engine, gmodel.metaBuilder.value, btp)

//                    val sett = getSetting(gmodel.settingFile.value)
//                    val kv = Kv().set(sett.getMap(""))
                    val metas = Kv.by("rootRoute", "sutra")
                            .set("rootRouteUpName", "Sutra")
                            .set("rootRouteLowName", "sutra")
                            .set("configName", "JxtproConfig")
                            .set("projectName", gmodel.projectName.value)
                            .set("projectFilterName", StrKit.firstCharToUpperCase(gmodel.projectName.value))
                            .set("projectFilterLowName", StrKit.firstCharToLowerCase(gmodel.projectName.value))
                            .set("projectPackage", gmodel.projectPackage.value)
                            .set("baseSrcPath", gmodel.baseSrcPath.value)
                            .set("baseResourcesPath", gmodel.baseResourcesPath.value)
                            .set("baseWebAppPath", gmodel.baseWebAppPath.value)
                            .set("baseWEBINFPath", gmodel.baseWEBINFPath.value)
                            .set("db_dev_dbType", "mysql")
                            .set("db_dev_jdbcUrl", "jdbc:mysql://localhost/aiopms?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false")
                            .set("db_dev_user", "root")
                            .set("db_dev_password", "root")
                            .set("db_dev_devMode", "true")
                            .set("db_pro_dbType", "mysql")
                            .set("db_pro_jdbcUrl", "jdbc:mysql://localhost/aiopms?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false")
                            .set("db_pro_user", "root")
                            .set("db_pro_password", "root")
                            .set("useShiro", "true")
                            .set("useCron4j", "true")
                            .set("usej2cache", "true")
                            .set("useSelect", "true")
                            .set("useZtree", "true")
                            .set("useMode", "m2c")

                    gen.build(metas)
//                    gen.build(kv)
                    fire(GenEvent("generate success! "))
                    Constants.closeDb(gmodel.dataSource.value)
                } catch (e: Exception) {
                    fire(GenEvent("generate failure" + e.toString()))
                    Constants.closeDb(gmodel.dataSource.value)
                }
            }
        }
    }

    //    test connection for sqlite, h2
    fun testDb1(): Boolean {
        if (FileUtil.exist(gmodel.dbname.value)) {
            testDb()
            return true
        } else {
            fire(GenEvent("testDb1()数据库文件不存在！"))
            return false
        }
    }

    /**
     * test connection for sqlite, h2
     */
    fun testDb() {
        try {
            genSrv.getCon()
            gmodel.dbOK.value = true
            genSrv.getDBs()
            genSrv.getAllTables()
            val num = tbls.size.toString()
            gmodel.tableCounts.value = "当前数据库共有${num}张表"
            fire(GenEvent("恭喜！数据库连接成功！"))
        } catch (e: Exception) {
            gmodel.dbOK.value = false
            fire(GenEvent("testDb() test connection failed: $e"))
        }
    }

    /**
     * test connection for postgresql, mysql,oracle,sqlserver
     */
    fun testDb2(): Boolean {
        try {
            genSrv.getCon()
            gmodel.dbOK.value = true
            genSrv.getDBs()
            fire(GenEvent("恭喜！数据库连接成功！"))
            return true
        } catch (e: Exception) {
            gmodel.dbOK.value = false
            fire(GenEvent("testDb() test connection failed: $e"))
            return false
        }
    }


}

fun getSetting(settingFile: String): Setting {
    return Setting(FileUtil.touch(settingFile), CharsetUtil.CHARSET_UTF_8, false)
}

